package fr.utbm.to52.android_bibtex.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import android.util.Log;
import fr.utbm.to52.android_bibtex.model.entry.Entry;
import fr.utbm.to52.android_bibtex.model.entry.EntryList;
import fr.utbm.to52.android_bibtex.model.entry.Field;

public class BibtexWriter {

	private static final String TAG = "BibtexWriter";

	public void write(File file) throws IOException {
		if (!file.exists()) {
			file.createNewFile();
		}

		FileWriter fstream;
		BufferedWriter out = null;
		try {
			fstream = new FileWriter(file);
			out = new BufferedWriter(fstream);
			Log.d(TAG, "Begin writing entries (size "+EntryList.getInstance().getEntryList().size());
			for (Entry e : EntryList.getInstance().getEntryList().values()) {
				Log.d(TAG, "Writing "+e.getKey());
				StringBuilder sb = new StringBuilder();
				sb.append("@"+e.getDefinition().getName()+"{");
				sb.append(e.getKey()+",\n");
				for (Field f : e.getFields().values()) {
					if (f.getValue() != null) {
						sb.append("\t"+f.getSpecification().getName()+" = {"+f.stringValue()+"},\n");
					}
				}
				sb.append("}\n\n");
				out.write(sb.toString());
				Log.d(TAG, "End writing "+e.getKey());
			}
			Log.d(TAG, "End writing entries");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (out != null) {
				out.close();
			}
		}
	}

}
